import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'package:todo_app/constants/Screen.dart';
import 'OverlaySupport.dart';

enum OverlayBottomSheetActionType {
  CANCEL,
  OK,
}

class OverlayBottomSheetAction<T> {

  OverlayBottomSheetAction({
    this.value,
    this.text,
    this.child,
  });

  OverlayBottomSheetAction.cancel({ this.text = "取消", this.child, this.value, this.type = OverlayBottomSheetActionType.CANCEL});

  T? value;
  String? text;
  Widget? child;
  OverlayBottomSheetActionType? type;
}

Future<T?> showOverlayBottomSheet<T>({
  List<OverlayBottomSheetAction<T>>? actions,
  Color? maskColor,
}) {
  OverlayEntry? overlay;
  var completer = Completer<T?>();

  var cancelAction = OverlayBottomSheetAction<T>.cancel();
  var _actions = <OverlayBottomSheetAction<T>>[]..addAll(actions ?? [])..add(cancelAction);

  var content = Container(
    child: Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: _actions.map((e) {
        return GestureDetector(
          onTap: () {
            overlay?.remove();
            completer.complete(e.value);
          },
          child: Container(
            height: Screen.sizeByDesign(58),
            margin: EdgeInsets.only(
              top: e.type == OverlayBottomSheetActionType.CANCEL ? Screen.sizeByDesign(15) : 0.0,
              bottom: Screen.sizeByDesign(8)
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(Screen.sizeByDesign(58/2))
            ),
            alignment: Alignment.center,
            child: e.child != null ? e.child : Text(e.text!),
          )
        );
      }).toList()
    ),
  );

  overlay = showOverlay(
    builder: (context, state) {
      return Container(
        alignment: Alignment.bottomCenter,
        color: maskColor ?? Colors.black.withOpacity(0.6),
        child: Container(
          margin: EdgeInsets.only(bottom: Screen.sizeByDesign(10)),
          width: Screen.sizeByDesign(384),
          child: SafeArea(
            top: false,
            bottom: true,
            child: DefaultTextStyle(
              style: TextStyle(fontSize: Screen.sizeByDesign(18), fontWeight: FontWeight.w400, color: Color(0xFF333333)),
              child: content,
            ),
          ),
        )
      );
    }
  );
  return completer.future;
}